import WebSocket, { WebSocketServer } from 'ws';
import { RpcFunc } from '../common';

export class GatewayManager {
    private static _instance: GatewayManager = null;

    static get inst() {
        if (!this._instance) {
            this._instance = new GatewayManager();
        }
        return this._instance;
    }

    init() {
        const wss = new WebSocketServer({ port: 4000 });

        wss.on('connection', (ws) => {
            ws.on('error', console.error);

            ws.on('message', (buffer: Buffer) => {
                this.handleMessage(ws, buffer);
            });
        });
    }

    handleMessage(ws: WebSocket, buffer: Buffer) {
        console.log(buffer.toString());
        const { name, data } = JSON.parse(buffer.toString());
        if (name === RpcFunc.enterGame) {
            // TODO:鉴权
        } else {
            // TODO:与game服务器通信
        }
        ws.send(buffer.toString());
    }
}